package cn.shentianlan.service.impl;

import cn.shentianlan.criteria.UserCriteria;
import cn.shentianlan.domain.dto.UserDTO;
import cn.shentianlan.domain.entity.Student;
import cn.shentianlan.domain.entity.Teacher;
import cn.shentianlan.domain.entity.User;
import cn.shentianlan.domain.enums.GenderCode;
import cn.shentianlan.domain.enums.RoleNameCode;
import cn.shentianlan.mapper.StudentMapper;
import cn.shentianlan.mapper.TeacherMapper;
import cn.shentianlan.mapper.UserMapper;
import cn.shentianlan.service.UserService;
import cn.shentianlan.utils.BaseUtils;
import cn.shentianlan.utils.DataUtils;
import cn.shentianlan.utils.Result;
import cn.shentianlan.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author 陈俊源
 * @Description TODO
 * @Date 2021/4/10
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private TeacherMapper teacherMapper;

    @Override
    public Result login(UserDTO userDTO) {  
        User userParameter = BaseUtils.copyProperties(userDTO, User.class);
        User user = userMapper.login(userParameter);
        if(user==null){
            return Result.fail("登录失败，用户账号或密码错误");
        }
        UserDTO dto = bulidUserDTO(user);
        return Result.success(dto);
    }

    @Override
    public Result getUserById(Long id) {
        if (id == null){
            return Result.fail("用户id为空，无法获取用户信息");
        }
        User user = userMapper.getUserById(id);
        if (user==null){
            return Result.fail("无法获取该id对应的用户信息");
        }
        UserDTO userDTO = bulidUserDTO(user);
        return Result.success(userDTO);
    }

    @Transactional
    @Override
    public Result deleteUserById(Long id){
        if (id == null){
            return Result.fail("用户id为空，无法执行删除操作");
        }
        User user = userMapper.getUserById(id);
        if (user == null){
            return Result.fail("未找到该id对应的用户信息，无法执行删除操作");
        }
        switch (user.getRoleName()){
            case 1:
                teacherMapper.deleteTeacherById(id);
                break;
            case 2:
                studentMapper.deleteStudentById(id);
                break;
            default:
                break;
        }
        userMapper.deleteUserById(id);
        return Result.success(id);
    }

    @Transactional
    @Override
    public Result saveOrUpdate(UserDTO userDTO) {
        Result result = checkUserInfo(userDTO);
        if (!Result.isSuccess(result)){
            return result;
        }
        Long id = DataUtils.assignId();
        User user = BaseUtils.copyProperties(userDTO, User.class);
        if (userDTO.getId()==null){
            user.setId(id);
            Boolean uniqueFlag = verifyUnique(user.getUsername());
            if (!uniqueFlag){
                return Result.fail("用户账号已存在");
            }
            userMapper.saveUser(user);
        }else {
            userMapper.updateUser(user);
        }
        switch (userDTO.getRoleName()){
            case 1:
                Teacher teacher = BaseUtils.copyProperties(userDTO, Teacher.class);
                if (userDTO.getId()==null){
                    teacher.setId(id);
                    teacherMapper.saveTeacher(teacher);
                }else{
                    Teacher teacherById = teacherMapper.getTeacherById(teacher.getId());
                    BaseUtils.copyProperties(teacher,teacherById,true);
                    teacherMapper.updateTeacher(teacherById);
                }
                break;
            case 2:
                Student student = BaseUtils.copyProperties(userDTO, Student.class);
                if (userDTO.getId()==null){
                    student.setId(id);
                    studentMapper.saveStudent(student);
                }else{
                    Student studentById = studentMapper.getStudentById(student.getId());
                    BaseUtils.copyProperties(student,studentById,true);
                    studentMapper.updateStudent(studentById);
                }
                break;
            default:
                break;
        }
        return Result.success(user.getId());
    }

    @Override
    public Result findUserByCriteria(UserCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(),criteria.getPageSize(),false);
        List<User> userList = userMapper.findUserByCriteria(criteria);
        Integer count = userMapper.getCount(criteria);
        List<UserDTO> userDTOList = new ArrayList<UserDTO>();
        for (User user :userList ) {
            UserDTO userDTO = bulidUserDTO(user);
            userDTOList.add(userDTO);
        }
        PageInfo<UserDTO> pageInfo = new PageInfo<UserDTO>(userDTOList);
        pageInfo.setTotal(count.longValue());
        return Result.success(pageInfo);
    }

    public UserDTO bulidUserDTO(User user){
        UserDTO userDTO = BaseUtils.copyProperties(user, UserDTO.class);
        userDTO.setGenderDec(GenderCode.getValue(user.getGender()));
        userDTO.setRoleNameDec(RoleNameCode.getValue(user.getRoleName()));
        return userDTO;
    }


    /**
     * 校验用户账号是否唯一
     * @param username
     * @return
     */
    public Boolean verifyUnique(String username){
        User user = userMapper.getUserByUsername(username);
        if (user==null){
            return true;
        }
        return false;
    }

    /**
     * 根据id获取姓名
     * @param id
     * @return
     */
    @Override
    public String getFullName(Long id){
        User userById = userMapper.getUserById(id);
        if (userById==null){
            return null;
        }
        return userById.getFullName();
    }



    //TODO 后期添加信息校验
    private Result checkUserInfo(UserDTO userDTO) {
        if (userDTO==null){
            return Result.fail("数据传输对象不能为空！");
        }
        if (!StringUtils.isNotNUllAndNotEntry(userDTO.getFullName())){
            return Result.fail("姓名不能为空！");
        }
        if (!StringUtils.isNotNUllAndNotEntry(userDTO.getUsername())){
            return Result.fail("用户账号不能为空！");
        }
        if(!StringUtils.isNotNUllAndNotEntry(userDTO.getPassword())){
            return Result.fail("用户密码不能为空！");
        }
        if (userDTO.getBirthDate()==null){
            return Result.fail("生日不能为空");
        }
        if (!StringUtils.isNotNUllAndNotEntry(userDTO.getContactWay())){
            return Result.fail("联系方式不能为空！");
        }
        if (userDTO.getRoleName()==null){
            return Result.fail("用户角色不能为空");
        }
        if(userDTO.getAge()==null){
            return Result.fail("用户年龄不能为空");
        }
//        if (userDTO.getBirthDay()==null){
//            return Result.fail("用户出生年月不能为空！");
//        }
        return Result.success();
    }
}
